//
//  LRTabBar.swift
//  WeiboX
//
//  Created by admin on 30/11/2016.
//  Copyright © 2016 iOS_Objective-C. All rights reserved.
//

import UIKit

protocol LRTabBarDelegate: NSObjectProtocol {
	func didSelectedComposeBtn()
}

class LRTabBar: UITabBar {
	
	weak var lrDelegate: LRTabBarDelegate?
	
	var callBack: (() -> ())?

	private lazy var composeBtn: UIButton = {
		let btn = UIButton()
		
		btn.addTarget(self, action: #selector(composeBtnAction(sender:)), for: .touchUpInside)
		
		btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), for: .normal)
		btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), for: .highlighted)
		
		btn.setImage(UIImage(named: "tabbar_compose_icon_add"), for: .normal)
		btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), for: .highlighted)
		
		btn.sizeToFit()
		return btn
	}()
	
	@objc private func composeBtnAction(sender:UIButton) {
		lrDelegate?.didSelectedComposeBtn()
		
		callBack!()
	}
	
	override init(frame: CGRect) {
		super.init(frame: frame)
		self.backgroundImage = UIImage(named: "tabbar_background")
		setupUI()
	}
	
	required init?(coder aDecoder: NSCoder) {
		fatalError("init(coder:) has not been implemented")
	}
	
	private func setupUI() {
		addSubview(composeBtn)
	}
	
	override func layoutSubviews() {
		super.layoutSubviews()
		
		composeBtn.centerX = width / 2
		composeBtn.centerY = height / 2
		
		let childViewW = width / 5
		
		var index = 0
		for childView in subviews {
			if childView.isKind(of: NSClassFromString("UITabBarButton")!) {
				childView.width = childViewW
				childView.x = CGFloat(index) * childViewW
				
				index += 1
				if index == 2 {
					index += 1
				}
			}
		}
	}
}
